package com.bml.architect.base;

import com.bml.architect.utils.MqConstants;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import javax.rmi.PortableRemoteObject;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;

/**
 * 异步发送，异步发送过后就不管了，但是会注册一个回调函数，通过回调函数来接受消息的发送状态
 */
public class AsyncProducer {

    public static void main(String[] args) {
        DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");
        try {
            producer.setNamesrvAddr(MqConstants.getNameServerAddr());
            producer.start();
            final CountDownLatch latch = new CountDownLatch(10);
            for (int i = 0; i < 10; i++) {
                final int index = i;
                Message message = new Message("TopicTest", "TagA", "async", ("hello rocketmq ,async send " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
                //异步发送，会注册一个回调函数，当消息接受成功过后可以调用回调函数方法
                producer.send(message, new SendCallback() {
                    @Override
                    public void onSuccess(SendResult sendResult) {
                        latch.countDown();
                        System.out.printf("%-10d OK %s %n", index, sendResult.getSendStatus());
                    }

                    @Override
                    public void onException(Throwable e) {
                        latch.countDown();
                        System.out.printf("%-10d Exception %s %n", index, e);
                        e.printStackTrace();
                    }
                });
            }
            System.out.println("消息发送完毕，等待回调....");
            latch.await();
            System.out.println("消息响应完成...");
            producer.shutdown();

        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
